package com.xuyl.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuyl.constant.MessageCode;
import com.xuyl.constant.MessageConstant;
import com.xuyl.domain.Operation;
import com.xuyl.domain.User;
import com.xuyl.entity.Result;
import com.xuyl.exception.BusinessException;
import com.xuyl.service.IOperationService;
import com.xuyl.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 业务操作记录，为实现撤销而服务，也能充当简单的日志
 *
 * @author nisemono
 * @date 2023-02-28 09:27
 */
@Slf4j
@RestController
@RequestMapping("/operations")
public class OperationController {

    @Autowired
    private IOperationService operationService;

    @Autowired
    private IUserService userService;

    @GetMapping
    public Result revocation() {
        boolean flag = false;
        QueryWrapper<Operation> lqw = new QueryWrapper<>();
        lqw.select("max(id) as id");
        Operation maxId = operationService.getOne(lqw);
        Operation lastOne = operationService.getById(maxId.getId());
        if (lastOne == null) {
            throw new BusinessException(MessageCode.BUSINESS_ERR, "当前无可撤回的操作");
        }
        if ("save".equals(lastOne.getOperation())) {
            String afterData = lastOne.getAfterData();
            User user = JSON.parseObject(afterData, User.class);
            flag = userService.deleteById(user.getId());
        }

        if ("delete".equals(lastOne.getOperation())) {
            String afterData = lastOne.getAfterData();
            User user = JSON.parseObject(afterData, User.class);
            flag = userService.updateDeletedUserInfoById(user.getId());
        }

        if ("update".equals(lastOne.getOperation())) {
            String beforeData = lastOne.getBeforeData();
            String afterData = lastOne.getAfterData();
            User userLatter = JSON.parseObject(afterData, User.class);
            User userFormer = JSON.parseObject(beforeData, User.class);
            userFormer.setVersion(userLatter.getVersion());
            flag = userService.updateUserInfoById(userFormer);
        }

        // 成功之后删除最后一条数据，实现多次撤销
        if (flag) {
            operationService.removeById(maxId.getId());
        }

        return new Result(flag, flag ? MessageConstant.REPEAL_OPERATION_SUCCESS : MessageConstant.REPEAL_OPERATION_FAILED);

    }

}
